import { createRouter, createWebHistory } from 'vue-router';
import HomeWork from '../views/HomeWork.vue';
import Login from '../views/Login.vue';
import AddWork from '../views/AddWork.vue';
import WorkDetail from '../views/WorkDetail.vue';
import UpdateWork from '../views/UpdateWork.vue';
import { useTokenStore } from '../stores/token';

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login,
    },
    {
      path: '/list',
      name: 'homeWorklist',
      component: HomeWork,
    },
    {
      path:'/addwork',
      name:'addwork',
      component: AddWork
    },
    {
      path:'/workdetail/:id',
      name:'workdetail',
      component: WorkDetail
    },
    {
      path:'/updatework/:id',
      name:'updatework',
      component: UpdateWork
    }
  ]
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const tokenStore = useTokenStore();
  const token = tokenStore.token;
  if (!token && to.name !== 'login') {
      // 如果没有token且要访问的不是登录页面，就跳转到登录页面
      next({ name: 'login' });
  } else {
      // 有token或者要访问的是登录页面，正常放行
      next();
  }
});

export default router
